package com.hxzy.filters;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.Claims;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.hxzy.common.consts.RedisConst;
import com.hxzy.common.util.ServletUtils;
import com.hxzy.config.IgnoreWhiteProperties;
import com.hxzy.util.ServletReactUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 网关鉴权(拦截是否有令牌)
 * 
 * @author admin
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered
{
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
    {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (matches(url, ignoreWhite.getWhites())){
            return chain.filter(exchange);
        }

        String token = getToken(request);
        if (StrUtil.isEmpty(token))
        {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        final JWT jwt = JWTUtil.parseToken(token);
        Object uuid = jwt.getPayload("uuid");
        if (uuid == null) {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }

        //取得令牌
        String redisKey = RedisConst.getRedisKey(RedisConst.ADMIN_LOGIN_KEY,uuid.toString());
        Boolean hasKey = this.redisTemplate.hasKey(redisKey);
        if(!hasKey){
            return unauthorizedResponse(exchange, "登录状态已过期");
        }

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private boolean matches(String str, List<String> strs){
        if (StrUtil.isBlank(str)) {
            return false;
        }
        for (String pattern : strs)
        {
            if (isMatch(pattern, str))
            {
                return true;
            }
        }
        return false;
    }


    /**
     * 判断url是否与规则配置:
     * ? 表示单个字符;
     * * 表示一层路径内的任意字符串，不可跨层级;
     * ** 表示任意层路径;
     *
     * @param pattern 匹配规则
     * @param url 需要匹配的url
     * @return
     */
    public  boolean isMatch(String pattern, String url)
    {
        AntPathMatcher matcher = new AntPathMatcher();
        return matcher.match(pattern, url);
    }





    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg)
    {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletReactUtils.webFluxResponseWriter(exchange.getResponse(), msg);
    }

    /**
     * 获取缓存key
     */
    private String getTokenKey(String token)
    {
        return RedisConst.ADMIN_LOGIN_KEY + token;
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request)
    {
        String token = request.getHeaders().getFirst("Authorization");
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith("Bearer "))
        {
            token = token.replaceFirst("Bearer " ,"");
        }
        return token;
    }

    @Override
    public int getOrder()
    {
        return -200;
    }
}